<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<style>
		.box {
			width: 400px;
			height: 150px;
			border: 1px solid black;
			background: #ccc;
			position: absolute;
			margin-left: -200px;
			margin-top: -75px;
			left: 50%;
			top: 50%;
			text-align: center;
			line-height: 150px;
		}
	</style>
	<script>
		window.onload = function() {
			let oBox = document.querySelector('.box');
			// 拖拽到box内
			oBox.ondragenter = function() {
				oBox.innerHTML = '松手上传'
			};
			// 从box内拖拽离开
			oBox.ondragleave = function() {
				oBox.innerHTML = '请拖到这里'
			};
			// 拖拽到box中并且悬停(鼠标没松手也没离开)，会一直不停的触发
			oBox.ondragover = function() {
				console.log('drag');
				return false;
			};
			// 拖拽到box中并且松手触发，需要在ondragover和drop中都阻止默认事件，ondragover阻止默认事件是为了drop成功触发，drop阻止默认事件是为了不打开拖拽进来的文件
			oBox.ondrop = function(ev) {
				
				
				// 拖拽文件的信息，和file表单组件的files相同
				// console.log(e.dataTransfer.files);

				let data = new FormData();
				Array.from(ev.dataTransfer.files).forEach(file => {
					data.append('fl', file);
				});

				let xhr = new XMLHttpRequest();
				xhr.open('post', 'http://localhost:8080/api', true);
				xhr.send(data);
				
				xhr.onreadystatechange = function() {
					if (xhr.readyState == 4) {
						if (xhr.status >= 200 && xhr.status < 300 || status == 304) {
							alert('上传成功')
						} else {
							alert('上传失败')
						}
					}
				}

				return false;
				
				
			}
		}
	</script>
</head>
<body>
	<div class="box">
		请拖到这里
	</div>
</body>
</html>